<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { agentLevelFormSchema } from './agentLevel.data';

  import { AddApi, EditApi } from '/@/api/set/account';
  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          const record = data.record;
          setFieldsValue({ ...record });
        }
      });
      const [registerForm, { setFieldsValue, resetFields, validate, validateFields }] = useForm({
        labelWidth: 100,
        schemas: agentLevelFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          console.log(validateFields(['password']));
          const values = await validate();
          if (values.id > 0) {
            await EditApi(values);
          } else {
            await AddApi(values);
          }
          closeModal();
          resetFields();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
